package com.xinyun.server;

import com.xinyun.server.protocol.ProtocolData;
import com.xinyun.server.protocol.ProtocolDataHeader;
import com.xinyun.server.thread.CheckBoardIdThread;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

/**
 * Created by bubusy on 16/5/21.
 */
public class ProtocolDecoder extends ByteToMessageDecoder {

    private Log log = LogFactory.getLog(ProtocolDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        log.debug("len:" + byteBuf.readableBytes());

        if (byteBuf.readableBytes() < 6) {
            return;
        }
        byteBuf.markReaderIndex();

        int length = byteBuf.readShortLE();
        int msgType = byteBuf.readByte();
        byte b4 = byteBuf.readByte();
        byte b5 = byteBuf.readByte();
        byte b6 = byteBuf.readByte();

        //System.out.println(length);

        if (byteBuf.readableBytes() < length) {
            byteBuf.resetReaderIndex();
            return;
        }
        ProtocolDataHeader header = new ProtocolDataHeader();
        header.setLength(length);
        header.setMsgType(msgType);
        header.setB4(b4);
        header.setB5(b5);
        header.setB6(b6);

        ProtocolData pd = new ProtocolData(header, byteBuf.readBytes(length));

        list.add(pd);
    }
}
